<template>
  <div class="login">
    <el-card class="box-card" style="width: 400px; padding: 20px">
      <template #header>
        <h2>登录</h2>
      </template>
      <el-form label-position="top">
        <el-form-item label="用户名">
          <el-input v-model="username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="password" type="password" />
        </el-form-item>
        <el-form-item style="display: flex">
          <el-button style="flex-grow: 1" type="primary" block @click="login">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';

import { useRouter } from 'vue-router';
import { getUsersLoginApi } from '@/api/users';

const router = useRouter();
// 如果登录
if (localStorage.token) {
  router.push('/');
}

// 登录
const username = ref('root');
const password = ref('123123');

async function login() {
  const res = await getUsersLoginApi({
    username: username.value,
    password: password.value,
  });
  // 保持token
  localStorage.token = res.data;
  ElMessage.success('登录成功');
  router.push('/');
}
</script>

<style scoped lang="scss">
.login {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
